package com.macro.mall.portal.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.Assist;
import com.macro.mall.mapper.RcRegistrationContentMapper;
import com.macro.mall.mapper.RcRegistrationConventionMapper;
import com.macro.mall.model.RcRegistrationContent;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.service.RcRegistrationContentService;
import com.macro.mall.portal.vo.StockTimeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * RcRegistrationContent的服务接口的实现类
 *
 * @author gaodx
 */
@Slf4j
@Service
public class RcRegistrationContentServiceImpl implements RcRegistrationContentService {

    private boolean isDebugEnabled;

    @Autowired
    private RcRegistrationContentMapper rcRegistrationContentMapper;
    // TODO 当你看到这个方法时你应该创建一个工具类做通用的方法,定义自己的返回格式化
    @Autowired
    private RcRegistrationConventionMapper rcRegistrationConventionMapper;


    @Override
    public List<RcRegistrationContent> find(RcRegistrationContent value, String queryType, Integer pageNum, Integer pageSize) {
        //TODO这里可以做通过Assist做添加查询
        List<RcRegistrationContent> result = null;
        Assist assist = new Assist();
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy("sort asc");
        try {
            if (!StrUtil.isBlankIfStr(value.getStatus())) {
                assist.andEq("status", value.getStatus());
            }
            if (!StrUtil.isBlankIfStr(value.getTitle())) {
                assist.andLike("title","%" + value.getTitle() + "%");
            }
            if (!StrUtil.isEmpty(value.getChannel())) {
                assist.andLike("channel", "%" + value.getChannel() + "%");
            }
            if(!StrUtil.isBlankIfStr(value.getIsRecommend())) {
                assist.andEq("is_Recommend",value.getIsRecommend());
            }
            if(!StrUtil.isBlankIfStr(value.getClassified())) {
                assist.andEq("classified",value.getClassified());
            }
            if(!StrUtil.isBlankIfStr(value.getCommunityId())) {
                assist.andEq("community_id",value.getCommunityId());
            }
            if ("0".equals(queryType)) {
                result = rcRegistrationContentMapper.selectRcRegistrationContent(assist);
                for(RcRegistrationContent a : result) {
                    Assist assist1 = new Assist();
                    assist1.andEq("handle_id",a.getId());
                    assist1.andEq("user_id",value.getUserId());
                    long count = rcRegistrationConventionMapper.getRcRegistrationConventionRowCount(assist1);
                    if(count != 0) {
                        a.setFlag("5");
                    }
                }
            } else {
                result = rcRegistrationContentMapper.selectRcRegistrationContentByUserId(value.getUserId(), queryType);
                for(RcRegistrationContent a : result) {
                    Assist assist1 = new Assist();
                    assist1.andEq("handle_id",a.getId());
                    assist1.andEq("user_id",value.getUserId());
                    long count = rcRegistrationConventionMapper.getRcRegistrationConventionRowCount(assist1);
                    if(count != 0) {
                        a.setFlag("5");
                    }
                }
            }
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行获取RcRegistrationContent数据集-->结果:", result);
        }
        return result;
    }

    @Override
    public RcRegistrationContent findOne(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过RcRegistrationContent的id获得RcRegistrationContent对象-->失败:id不能为空");
            }
            Asserts.fail("执行通过RcRegistrationContent的id获得RcRegistrationContent对象-->失败:id不能为空");
        }
        RcRegistrationContent result = null;
        Assist assist = new Assist();
        try {
            result = rcRegistrationContentMapper.selectRcRegistrationContentById(id);
            assist.andEq("handle_id", id);
            Long count = rcRegistrationConventionMapper.getRcRegistrationConventionRowCount(assist);
            SecurityContext ctx = SecurityContextHolder.getContext();
            Authentication auth = ctx.getAuthentication();
            MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
            assist.andEq("user_id",memberDetails.getUmsMember().getId());
            long count1 = rcRegistrationConventionMapper.getRcRegistrationConventionRowCount(assist);
            if(count1 != 0) {
                result.setFlag("5");
            }
            result.setRegistrationNum(count.intValue());
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过RcRegistrationContent的id获得RcRegistrationContent对象-->结果:", result);
        }
        return result;
    }

    @Override
    public CommonResult saveNotNull(RcRegistrationContent value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行将RcRegistrationContent中属性值不为null的数据保存到数据库-->失败:对象不能为空");
            }
            Asserts.fail("失败:对象不能为空");
        }
        int result = 0;
        try {
            result = rcRegistrationContentMapper.insertNotNullRcRegistrationContent(value);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行将RcRegistrationContent中属性值不为null的数据保存到数据库-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult updateNotNullById(RcRegistrationContent value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行通过RcRegistrationContent的id更新RcRegistrationContent中属性不为null的数据-->失败:对象为null");
            }
            Asserts.fail("执行通过RcRegistrationContent的id更新RcRegistrationContent中属性不为null的数据-->失败:对象为null");
        }
        int result = 0;
        try {
            result = rcRegistrationContentMapper.updateNotNullRcRegistrationContentById(value);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过RcRegistrationContent的id更新RcRegistrationContent中属性不为null的数据-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult deleteById(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过RcRegistrationContent的id删除RcRegistrationContent-->失败:id不能为空");
            }
            Asserts.fail("执行通过RcRegistrationContent的id删除RcRegistrationContent-->失败:id不能为空");
        }
        int result = 0;
        try {
            result = rcRegistrationContentMapper.deleteRcRegistrationContentById(id);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过RcRegistrationContent的id删除RcRegistrationContent-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult getStockTime(Integer id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过RcRegistrationContent的id删除RcRegistrationContent-->失败:id不能为空");
            }
            Asserts.fail("执行通过RcRegistrationContent的id删除RcRegistrationContent-->失败:id不能为空");
        }
        RcRegistrationContent result = null;
        Map<String,Object> map = new HashMap<>();
        try {
            result = rcRegistrationContentMapper.selectRcRegistrationContentById(id);
            getData(result, map);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过RcRegistrationContent的id删除RcRegistrationContent-->结果:", result);
        }
        return CommonResult.success(map);
    }

    private void getData(RcRegistrationContent result, Map<String, Object> map) {
        List<StockTimeVO> allDay;
        Date date = new Date();
        DateTime newDate2 = DateUtil.offsetDay(date, 6);
        String format1 = DateUtil.format(date, "yyyy-MM-dd");
        String format2 = DateUtil.format(newDate2, "yyyy-MM-dd");
        List<StockTimeVO> twoDaysDay = getTwoDaysDay(format1, format2);
        allDay = getTwoDaysDay(DateUtil.format(result.getStime(), "yyyy-MM-dd"), DateUtil.format(result.getEtime(), "yyyy-MM-dd"));
        for (StockTimeVO day : twoDaysDay) {
            day.setWeek(getWeek(DateUtil.parseDate(day.getStockDate())));
            for (StockTimeVO days : allDay) {
                if(day.getStockDate().equals(days.getStockDate())) {
                    day.setStatus("1");
                    break;
                } else{
                    day.setStatus("2");
                }
            }
            String toDay = DateUtil.format(date, "yyyy-MM-dd");
            if(day.getStockDate().equals(toDay)) {
                day.setWeek("今日");
            }
        }
        Collections.sort(twoDaysDay, Comparator.comparing(StockTimeVO::getStockDate));
        map.put("stockArray",twoDaysDay);
        map.put("mornTime",result.getMornTime());
        map.put("afternoonTime",result.getAfternoonTime());
    }

    /**
     * 返回两个时间间隔内的所有日期
     *
     * @param dateStart eg：2017-1-1
     * @param dateEnd   eg:2019-9-25
     * @return java.util.List<java.lang.String>
     * @Title: getTwoDaysDay
     */

    public List<StockTimeVO> getTwoDaysDay(String dateStart, String dateEnd) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        List<StockTimeVO> dateList = new ArrayList();

        try {
            Date dateOne = sdf.parse(dateStart);
            Date dateTwo = sdf.parse(dateEnd);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateOne);

            dateList.add(StockTimeVO.builder().stockDate(sdf.format(dateOne)).build());
            while (calendar.getTime().before(dateTwo)) {
                calendar.add(Calendar.DAY_OF_MONTH, +1);
                dateList.add(StockTimeVO.builder().stockDate(sdf.format(calendar.getTime())).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateList;
    }

    public String getWeek(Date date){
        String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if(week_index<0){
            week_index = 0;
        }
        return weeks[week_index];
    }

}